"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _objectSpread4 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _jsxRuntime = require("react/jsx-runtime");

var _icons = require("@ant-design/icons");

var _proProvider = require("@ant-design/pro-provider");

var _proUtils = require("@ant-design/pro-utils");

var _antdV = require("antd-v4");

var _classnames = _interopRequireDefault(require("classnames"));

var _omit = _interopRequireDefault(require("omit.js"));

var _react = require("react");

var _container = _interopRequireDefault(require("../../container"));

var _index = require("../../utils/index");

require("./index.less");

var _excluded = ["key", "dataIndex", "children"];

var ToolTipIcon = function ToolTipIcon(_ref) {
  var title = _ref.title,
      show = _ref.show,
      children = _ref.children,
      columnKey = _ref.columnKey,
      fixed = _ref.fixed;

  var _Container$useContain = _container.default.useContainer(),
      columnsMap = _Container$useContain.columnsMap,
      setColumnsMap = _Container$useContain.setColumnsMap;

  if (!show) {
    return null;
  }

  return (0, _jsxRuntime.jsx)(_antdV.Tooltip, {
    title: title,
    children: (0, _jsxRuntime.jsx)("span", {
      onClick: function onClick(e) {
        e.stopPropagation();
        e.preventDefault();
        var config = columnsMap[columnKey] || {};
        var disableIcon = typeof config.disable === 'boolean' && config.disable;
        if (disableIcon) return;
        var columnKeyMap = (0, _objectSpread4.default)((0, _objectSpread4.default)({}, columnsMap), {}, (0, _defineProperty2.default)({}, columnKey, (0, _objectSpread4.default)((0, _objectSpread4.default)({}, config), {}, {
          fixed: fixed
        })));
        setColumnsMap(columnKeyMap);
      },
      children: children
    })
  });
};

var CheckboxListItem = function CheckboxListItem(_ref2) {
  var columnKey = _ref2.columnKey,
      isLeaf = _ref2.isLeaf,
      title = _ref2.title,
      className = _ref2.className,
      fixed = _ref2.fixed;
  var intl = (0, _proProvider.useIntl)();
  var dom = (0, _jsxRuntime.jsxs)("span", {
    className: "".concat(className, "-list-item-option"),
    children: [(0, _jsxRuntime.jsx)(ToolTipIcon, {
      columnKey: columnKey,
      fixed: "left",
      title: intl.getMessage('tableToolBar.leftPin', '固定在列首'),
      show: fixed !== 'left',
      children: (0, _jsxRuntime.jsx)(_icons.VerticalAlignTopOutlined, {})
    }), (0, _jsxRuntime.jsx)(ToolTipIcon, {
      columnKey: columnKey,
      fixed: undefined,
      title: intl.getMessage('tableToolBar.noPin', '不固定'),
      show: !!fixed,
      children: (0, _jsxRuntime.jsx)(_icons.VerticalAlignMiddleOutlined, {})
    }), (0, _jsxRuntime.jsx)(ToolTipIcon, {
      columnKey: columnKey,
      fixed: "right",
      title: intl.getMessage('tableToolBar.rightPin', '固定在列尾'),
      show: fixed !== 'right',
      children: (0, _jsxRuntime.jsx)(_icons.VerticalAlignBottomOutlined, {})
    })]
  });
  return (0, _jsxRuntime.jsxs)("span", {
    className: "".concat(className, "-list-item"),
    children: [(0, _jsxRuntime.jsx)("div", {
      className: "".concat(className, "-list-item-title"),
      children: title
    }), !isLeaf ? dom : null]
  }, columnKey);
};

var CheckboxList = function CheckboxList(_ref3) {
  var _treeDataConfig$list, _treeDataConfig$list2;

  var list = _ref3.list,
      draggable = _ref3.draggable,
      checkable = _ref3.checkable,
      className = _ref3.className,
      _ref3$showTitle = _ref3.showTitle,
      showTitle = _ref3$showTitle === void 0 ? true : _ref3$showTitle,
      listTitle = _ref3.title,
      _ref3$listHeight = _ref3.listHeight,
      listHeight = _ref3$listHeight === void 0 ? 280 : _ref3$listHeight;

  var _Container$useContain2 = _container.default.useContainer(),
      columnsMap = _Container$useContain2.columnsMap,
      setColumnsMap = _Container$useContain2.setColumnsMap,
      sortKeyColumns = _Container$useContain2.sortKeyColumns,
      setSortKeyColumns = _Container$useContain2.setSortKeyColumns;

  var show = list && list.length > 0;
  var treeDataConfig = (0, _react.useMemo)(function () {
    if (!show) return {};
    var checkedKeys = [];

    var loopData = function loopData(data, parentConfig) {
      return data.map(function (_ref4) {
        var _config$disable;

        var key = _ref4.key,
            dataIndex = _ref4.dataIndex,
            children = _ref4.children,
            rest = (0, _objectWithoutProperties2.default)(_ref4, _excluded);
        var columnKey = (0, _index.genColumnKey)(key, rest.index);
        var config = columnsMap[columnKey || 'null'] || {
          show: true
        };

        if (config.show !== false && (parentConfig === null || parentConfig === void 0 ? void 0 : parentConfig.show) !== false && !children) {
          checkedKeys.push(columnKey);
        }

        var item = (0, _objectSpread4.default)((0, _objectSpread4.default)({
          key: columnKey
        }, (0, _omit.default)(rest, ['className'])), {}, {
          selectable: false,
          disabled: config.disable === true,
          disableCheckbox: typeof config.disable === 'boolean' ? config.disable : (_config$disable = config.disable) === null || _config$disable === void 0 ? void 0 : _config$disable.checkbox,
          isLeaf: parentConfig ? true : undefined
        });

        if (children) {
          item.children = loopData(children, config);
        }

        return item;
      });
    };

    return {
      list: loopData(list),
      keys: checkedKeys
    };
  }, [columnsMap, list, show]);
  /** 移动到指定的位置 */

  var move = (0, _proUtils.useRefFunction)(function (id, targetId, dropPosition) {
    var newMap = (0, _objectSpread4.default)({}, columnsMap);
    var newColumns = (0, _toConsumableArray2.default)(sortKeyColumns);
    var findIndex = newColumns.findIndex(function (columnKey) {
      return columnKey === id;
    });
    var targetIndex = newColumns.findIndex(function (columnKey) {
      return columnKey === targetId;
    });
    var isDownWord = dropPosition > targetIndex;
    if (findIndex < 0) return;
    var targetItem = newColumns[findIndex];
    newColumns.splice(findIndex, 1);

    if (dropPosition === 0) {
      newColumns.unshift(targetItem);
    } else {
      newColumns.splice(isDownWord ? targetIndex : targetIndex + 1, 0, targetItem);
    } // 重新生成排序数组


    newColumns.forEach(function (key, order) {
      newMap[key] = (0, _objectSpread4.default)((0, _objectSpread4.default)({}, newMap[key] || {}), {}, {
        order: order
      });
    }); // 更新数组

    setColumnsMap(newMap);
    setSortKeyColumns(newColumns);
  });
  /** 选中反选功能 */

  var onCheckTree = (0, _proUtils.useRefFunction)(function (e) {
    var columnKey = e.node.key;
    var newSetting = (0, _objectSpread4.default)({}, columnsMap[columnKey]);
    newSetting.show = e.checked;
    setColumnsMap((0, _objectSpread4.default)((0, _objectSpread4.default)({}, columnsMap), {}, (0, _defineProperty2.default)({}, columnKey, newSetting)));
  });

  if (!show) {
    return null;
  }

  var listDom = (0, _jsxRuntime.jsx)(_antdV.Tree, {
    itemHeight: 24,
    draggable: draggable && !!((_treeDataConfig$list = treeDataConfig.list) === null || _treeDataConfig$list === void 0 ? void 0 : _treeDataConfig$list.length) && ((_treeDataConfig$list2 = treeDataConfig.list) === null || _treeDataConfig$list2 === void 0 ? void 0 : _treeDataConfig$list2.length) > 1,
    checkable: checkable,
    onDrop: function onDrop(info) {
      var dropKey = info.node.key;
      var dragKey = info.dragNode.key;
      var dropPosition = info.dropPosition,
          dropToGap = info.dropToGap;
      var position = dropPosition === -1 || !dropToGap ? dropPosition + 1 : dropPosition;
      move(dragKey, dropKey, position);
    },
    blockNode: true,
    onCheck: function onCheck(_, e) {
      return onCheckTree(e);
    },
    checkedKeys: treeDataConfig.keys,
    showLine: false,
    titleRender: function titleRender(_node) {
      var node = (0, _objectSpread4.default)((0, _objectSpread4.default)({}, _node), {}, {
        children: undefined
      });
      return (0, _jsxRuntime.jsx)(CheckboxListItem, (0, _objectSpread4.default)((0, _objectSpread4.default)({
        className: className
      }, node), {}, {
        title: (0, _proUtils.runFunction)(node.title, node),
        columnKey: node.key
      }));
    },
    height: listHeight,
    treeData: treeDataConfig.list
  });
  return (0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [showTitle && (0, _jsxRuntime.jsx)("span", {
      className: "".concat(className, "-list-title"),
      children: listTitle
    }), listDom]
  });
};

var GroupCheckboxList = function GroupCheckboxList(_ref5) {
  var localColumns = _ref5.localColumns,
      className = _ref5.className,
      draggable = _ref5.draggable,
      checkable = _ref5.checkable,
      listsHeight = _ref5.listsHeight;
  var rightList = [];
  var leftList = [];
  var list = [];
  var intl = (0, _proProvider.useIntl)();
  localColumns.forEach(function (item) {
    /** 不在 setting 中展示的 */
    if (item.hideInSetting) {
      return;
    }

    var fixed = item.fixed;

    if (fixed === 'left') {
      leftList.push(item);
      return;
    }

    if (fixed === 'right') {
      rightList.push(item);
      return;
    }

    list.push(item);
  });
  var showRight = rightList && rightList.length > 0;
  var showLeft = leftList && leftList.length > 0;
  return (0, _jsxRuntime.jsxs)("div", {
    className: (0, _classnames.default)("".concat(className, "-list"), (0, _defineProperty2.default)({}, "".concat(className, "-list-group"), showRight || showLeft)),
    children: [(0, _jsxRuntime.jsx)(CheckboxList, {
      title: intl.getMessage('tableToolBar.leftFixedTitle', '固定在左侧'),
      list: leftList,
      draggable: draggable,
      checkable: checkable,
      className: className,
      listHeight: listsHeight
    }), (0, _jsxRuntime.jsx)(CheckboxList, {
      list: list,
      draggable: draggable,
      checkable: checkable,
      title: intl.getMessage('tableToolBar.noFixedTitle', '不固定'),
      showTitle: showLeft || showRight,
      className: className,
      listHeight: listsHeight
    }), (0, _jsxRuntime.jsx)(CheckboxList, {
      title: intl.getMessage('tableToolBar.rightFixedTitle', '固定在右侧'),
      list: rightList,
      draggable: draggable,
      checkable: checkable,
      className: className,
      listHeight: listsHeight
    })]
  });
};

function ColumnSetting(props) {
  var _props$checkable, _props$draggable;

  var columnRef = (0, _react.useRef)({});

  var counter = _container.default.useContainer();

  var localColumns = props.columns;
  var _props$checkedReset = props.checkedReset,
      checkedReset = _props$checkedReset === void 0 ? true : _props$checkedReset;
  var columnsMap = counter.columnsMap,
      setColumnsMap = counter.setColumnsMap,
      clearPersistenceStorage = counter.clearPersistenceStorage;
  (0, _react.useEffect)(function () {
    var _counter$propsRef$cur, _counter$propsRef$cur2;

    if ((_counter$propsRef$cur = counter.propsRef.current) === null || _counter$propsRef$cur === void 0 ? void 0 : (_counter$propsRef$cur2 = _counter$propsRef$cur.columnsState) === null || _counter$propsRef$cur2 === void 0 ? void 0 : _counter$propsRef$cur2.value) {
      var _counter$propsRef$cur3, _counter$propsRef$cur4;

      columnRef.current = JSON.parse(JSON.stringify(((_counter$propsRef$cur3 = counter.propsRef.current) === null || _counter$propsRef$cur3 === void 0 ? void 0 : (_counter$propsRef$cur4 = _counter$propsRef$cur3.columnsState) === null || _counter$propsRef$cur4 === void 0 ? void 0 : _counter$propsRef$cur4.value) || {}));
    } // eslint-disable-next-line react-hooks/exhaustive-deps

  }, []);
  /**
   * 设置全部选中，或全部未选中
   *
   * @param show
   */

  var setAllSelectAction = (0, _proUtils.useRefFunction)(function () {
    var show = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
    var columnKeyMap = {};

    var loopColumns = function loopColumns(columns) {
      columns.forEach(function (_ref6) {
        var key = _ref6.key,
            fixed = _ref6.fixed,
            index = _ref6.index,
            children = _ref6.children;
        var columnKey = (0, _index.genColumnKey)(key, index);

        if (columnKey) {
          columnKeyMap[columnKey] = {
            show: show,
            fixed: fixed
          };
        }

        if (children) {
          loopColumns(children);
        }
      });
    };

    loopColumns(localColumns);
    setColumnsMap(columnKeyMap);
  });
  /** 全选和反选 */

  var checkedAll = (0, _proUtils.useRefFunction)(function (e) {
    if (e.target.checked) {
      setAllSelectAction();
    } else {
      setAllSelectAction(false);
    }
  });
  /** 重置项目 */

  var clearClick = (0, _proUtils.useRefFunction)(function () {
    clearPersistenceStorage === null || clearPersistenceStorage === void 0 ? void 0 : clearPersistenceStorage();
    setColumnsMap(columnRef.current);
  }); // 未选中的 key 列表

  var unCheckedKeys = Object.values(columnsMap).filter(function (value) {
    return !value || value.show === false;
  }); // 是否已经选中

  var indeterminate = unCheckedKeys.length > 0 && unCheckedKeys.length !== localColumns.length;
  var intl = (0, _proProvider.useIntl)();

  var _useContext = (0, _react.useContext)(_antdV.ConfigProvider.ConfigContext),
      getPrefixCls = _useContext.getPrefixCls;

  var className = getPrefixCls('pro-table-column-setting');
  return (0, _jsxRuntime.jsx)(_antdV.Popover, {
    arrowPointAtCenter: true,
    title: (0, _jsxRuntime.jsxs)("div", {
      className: "".concat(className, "-title"),
      children: [(0, _jsxRuntime.jsx)(_antdV.Checkbox, {
        indeterminate: indeterminate,
        checked: unCheckedKeys.length === 0 && unCheckedKeys.length !== localColumns.length,
        onChange: function onChange(e) {
          return checkedAll(e);
        },
        children: intl.getMessage('tableToolBar.columnDisplay', '列展示')
      }), checkedReset ? (0, _jsxRuntime.jsx)("a", {
        onClick: clearClick,
        className: "".concat(className, "-action-rest-button"),
        children: intl.getMessage('tableToolBar.reset', '重置')
      }) : null, (props === null || props === void 0 ? void 0 : props.extra) ? (0, _jsxRuntime.jsx)(_antdV.Space, {
        size: 12,
        align: "center",
        children: props.extra
      }) : null]
    }),
    overlayClassName: "".concat(className, "-overlay"),
    trigger: "click",
    placement: "bottomRight",
    content: (0, _jsxRuntime.jsx)(GroupCheckboxList, {
      checkable: (_props$checkable = props.checkable) !== null && _props$checkable !== void 0 ? _props$checkable : true,
      draggable: (_props$draggable = props.draggable) !== null && _props$draggable !== void 0 ? _props$draggable : true,
      className: className,
      localColumns: localColumns,
      listsHeight: props.listsHeight
    }),
    children: props.children || (0, _jsxRuntime.jsx)(_antdV.Tooltip, {
      title: intl.getMessage('tableToolBar.columnSetting', '列设置'),
      children: (0, _jsxRuntime.jsx)(_icons.SettingOutlined, {})
    })
  });
}

var _default = ColumnSetting;
exports.default = _default;